package com.gardenguell.salad.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
import com.gardenguell.salad.R;
import com.gardenguell.salad.app.AppConstant;
import com.gardenguell.salad.data.client.SaladClient;
import com.gardenguell.salad.data.model.Box;
import com.gardenguell.salad.data.model.EnviromentParams;
import com.gardenguell.salad.data.model.Unit;
import com.gardenguell.salad.data.volley.OnErrorResponse;
import com.gardenguell.salad.data.volley.OnSuccessResponse;
import com.gardenguell.salad.ui.activity.base.BaseActivity;
import com.gardenguell.salad.ui.view.*;
import com.gardenguell.salad.util.SharedPreferenceUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by absurd on 2015/11/28.
 */
public class ControlActivity extends BaseActivity {

    private static final int TASK_DELAY = 5 * 1000;

    private Toolbar mToolbar;
    private CollapsingToolbarLayout mCollapsingToolbarLayout;
    private DataGraph mDataGraph;

    private SaladClient mClient = new SaladClient();
    private Box mBox;
    private int mUnitId;
    private Unit mUnit;

    private Timer mTimer = new Timer();
    private TimerTask mTask = new TimerTask() {
        @Override
        public void run() {
            SaladClient client = new SaladClient();
            client.getUnitEnvParams(mBox.getMac(), mUnitId, getUsername(), new OnSuccessResponse<EnviromentParams>() {
                @Override
                public void onSuccessWithObj(EnviromentParams obj) {
                    super.onSuccessWithObj(obj);
                    if(ControlActivity.this != null && !ControlActivity.this.isFinishing()){
                        if (obj != null) {
                            //Toast.makeText(ControlActivity.this, obj.toString(), Toast.LENGTH_SHORT).show();
                            mDataGraph.bindData(0, obj);
                        }
                    }
                }
            }, new OnErrorResponse(){
                @Override
                public void onError(int errorCode) {
                }
            });
        }
    };


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_control);

        Intent intent = getIntent();
        if(intent != null && intent.getExtras() != null) {
            mBox = (Box) getIntent().getExtras().get("box");
            mUnitId = getIntent().getExtras().getInt("unitId");
            mUnit = (Unit) getIntent().getExtras().get("unit");
        }

        mToolbar = (Toolbar)findViewById(R.id.toolbar);
        mCollapsingToolbarLayout = (CollapsingToolbarLayout)findViewById(R.id.collapsing_toolbar);
        mCollapsingToolbarLayout.setTitle(getString(R.string.app_name));

        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ControlActivity.this.onBackPressed();
            }
        });

        ((ImageView)findViewById(R.id.btn_temperature)).setImageResource(R.mipmap.ic_temperature_pressed);

        mDataGraph = (DataGraph)findViewById(R.id.data_graph);

        mTimer.schedule(mTask, 0, TASK_DELAY);
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_control, menu);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()){
            case R.id.action_auto:
                setConfigSchema(0, R.string.tip_set_auto);
                Toast.makeText(this, R.string.tip_set_auto, Toast.LENGTH_SHORT).show();
                return true;
            case R.id.action_iron:
                setConfigSchema(2, R.string.tip_set_iron);
                Toast.makeText(this, R.string.tip_set_iron, Toast.LENGTH_SHORT).show();
                break;
            case R.id.action_blood:
                setConfigSchema(3, R.string.tip_set_blood);
                Toast.makeText(this, R.string.tip_set_blood, Toast.LENGTH_SHORT).show();
                break;
            case R.id.action_manual:
                final MaterialDialog controlDialog = new MaterialDialog(this);
                View view = LayoutInflater.from(this)
                        .inflate(R.layout.dia_conrol,
                                null);
                final TagSeekBar temperatureSb = (TagSeekBar) view.findViewById(R.id.sb_temperature);
                final TagSeekBar illuminationSb = (TagSeekBar)view.findViewById(R.id.sb_illumination);
                final TagSeekBar humiditySb = (TagSeekBar)view.findViewById(R.id.sb_humidity);
                final TagSeekBar nutrientSb = (TagSeekBar)view.findViewById(R.id.sb_nutrient);
                mClient.getUnitEnvParams(mBox.getMac(), mUnitId, getUsername(),
                        new OnSuccessResponse<EnviromentParams>() {
                            @Override
                            public void onSuccessWithObj(EnviromentParams ep) {
                                super.onSuccessWithObj(ep);
                                if(ep != null) {
                                    temperatureSb.setCur(ep.getTemperature());
                                    humiditySb.setCur(ep.getHumidity());
                                    illuminationSb.setCur(ep.getIllumination());
                                    nutrientSb.setCur(ep.getNutrient());
                                }
                            }
                        }, new OnErrorResponse() {
                            @Override
                            public void onError(int errorCode) {
                                EnviromentParams ep  = new EnviromentParams();
                                temperatureSb.setCur(ep.getTemperature());
                                humiditySb.setCur(ep.getHumidity());
                                illuminationSb.setCur(ep.getIllumination());
                                nutrientSb.setCur(ep.getNutrient());
                            }
                        });

                controlDialog.setView(view).setPositiveButton(R.string.ok, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mClient.setConfigSchema(mBox.getMac(), mUnitId, getUsername(), 2,
                                new OnSuccessResponse() {
                                    @Override
                                    public void onSuccessWithNoBody() {
                                        super.onSuccessWithNoBody();
                                        Toast.makeText(ControlActivity.this, R.string.tip_set_mannual, Toast.LENGTH_SHORT).show();
                                        EnviromentParams ep = new EnviromentParams();
                                        ep.setVegetableId(mUnit.getVegetableId());
                                        ep.setTemperature(temperatureSb.getCur());
                                        ep.setHumidity(humiditySb.getCur());
                                        ep.setIllumination(illuminationSb.getCur());
                                        ep.setNutrient(nutrientSb.getCur());
                                        mClient.setUnitEnvParams(mBox.getMac(), mUnitId, getUsername(),ep,
                                                new OnSuccessResponse(){
                                                    @Override
                                                    public void onSuccessWithNoBody() {
                                                        super.onSuccessWithNoBody();
                                                    }
                                                }, ControlActivity.this);
                                    }
                                }, new OnErrorResponse() {
                                    @Override
                                    public void onError(int errorCode) {
                                        EnviromentParams ep = new EnviromentParams();
                                        ep.setVegetableId(mUnit.getVegetableId());
                                        ep.setTemperature(temperatureSb.getCur());
                                        ep.setHumidity(humiditySb.getCur());
                                        ep.setIllumination(illuminationSb.getCur());
                                        ep.setNutrient(nutrientSb.getCur());
                                        mClient.setUnitEnvParams(mBox.getMac(), mUnitId, getUsername(),ep,
                                                new OnSuccessResponse(){
                                                    @Override
                                                    public void onSuccessWithNoBody() {
                                                        super.onSuccessWithNoBody();
                                                    }
                                                },ControlActivity.this);
                                    }
                                });

                        controlDialog.dismiss();


                    }
                }).setNegativeButton(R.string.cancel, new View.OnClickListener(){
                    @Override
                    public void onClick(View view) {
                        controlDialog.dismiss();

                    }
                }).show();
                controlDialog.setCanceledOnTouchOutside(false);
                return true;

        }
        return super.onOptionsItemSelected(item);
    }


    private void setConfigSchema(int i, final int res){
        mClient.setConfigSchema(mBox.getMac(), mUnitId, getUsername(), i,
                new OnSuccessResponse() {
                    @Override
                    public void onSuccessWithNoBody() {
                        super.onSuccessWithNoBody();
                        Toast.makeText(ControlActivity.this, res, Toast.LENGTH_SHORT).show();

                    }
                }, this);
    }




    @Override
    protected void onDestroy() {
        super.onDestroy();
        mTask.cancel();
    }
}